﻿using Admin.NET.Core;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MOKA.TPM.Entity;
using MOKA.TPM.Utility;
using MOKA.TPM.Utility.Const;
using Newtonsoft.Json;
using SqlSugar;
using System.Data;
using System.Net;

namespace MOKA.TPM.Service;

/// <summary>
/// 非采物料服务 🧩
/// </summary>
[ApiDescriptionSettings(TPMConst.GroupName, Name = "Menu", Order = 305)]
[NonUnify]
public class MenuService : IDynamicApiController, ITransient
{
    private readonly ISqlSugarClient _sqlSugarClient;
    private readonly IHttpContextAccessor _httpContextAccessor;
    private readonly UserManager _userManager;
    private SqlSugarScopeProvider Context;

    public MenuService(UserManager userManager, SqlSugarRepository<Parts> PartsRep, IHttpContextAccessor httpContextAccessor)
    {
        _userManager = userManager;
        _httpContextAccessor = httpContextAccessor;

        var iTenant = SqlSugarSetup.ITenant;
        Context = iTenant.GetConnectionScope(TPMConst.MESBaseDB);
    }

    [AllowAnonymous]
    [ApiDescriptionSettings(Name = "GetMenu"), HttpGet]
    public async Task<List<MenuCs>> GetMenuAsync()
    {
        var request = _httpContextAccessor.HttpContext.Request;
        // 你可以在这里使用 request 对象
        string ClientToken = WebUtility.UrlDecode(request.Headers["token"].ToString());
        UserToken TokenCs = JsonConvert.DeserializeObject<UserToken>(ClientToken);
        string UserAccount = TokenCs.UserAccount;
        string AppName = string.IsNullOrEmpty(TokenCs.AppName) ? "ApiCloud" : "TPM";
        string Sql = @"select * from MESBaseDB.[dbo].[WebModule] where ModelId in
                         (select ModelId from MESBaseDB.dbo.WebRolePermission as RP join MESBaseDB.dbo.WebUserRoles as UR on RP.RoleId = UR.RoleId  where UR.UserNo = '{0}'
                         union select ModelId from MESBaseDB.[dbo].[WebUserPermission] as UP where UP.UserName = '{0}') and ModelType=2 and remark='" + AppName + "'  order by Sort";

        LogHelper.Write("GetMenu", string.Format("SQL={0}", Sql));
        DataTable Dt = await Context.Ado.GetDataTableAsync(string.Format(Sql, UserAccount));

        List<MenuCs> List = new List<MenuCs>();
        if (Dt.Rows.Count > 0)
        {
            for (int i = 0; i < Dt.Rows.Count; i++)
            {
                MenuCs menu = new MenuCs();
                menu.Title = Dt.Rows[i]["ModelName"].ToString();
                menu.Url = Dt.Rows[i]["ActionUrl"].ToString();
                List.Add(menu);
            }
        }
        return List;
    }

    public class MenuCs
    {
        public string Url { get; set; }
        public string Title { get; set; }
    }
}